﻿//18.四数之和
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> ans;

        sort(nums.begin(), nums.end());

        int len = nums.size();
        for (int i = 0; i < len - 3;)
        {
            if (nums[i] > 0 && nums[i] > target)
            {
                break;
            }

            for (int j = i + 1; j < len - 2;)
            {
                if (nums[i] + nums[j] > 0 && nums[i] + nums[j] > target)
                {
                    break;
                }

                int left = j + 1, right = len - 1;
                while (left < right)
                {
                    long long aim = (long long)target - (nums[i] + nums[j]);
                    if (nums[left] + nums[right] < aim)
                    {
                        left++;
                    }
                    else if (nums[left] + nums[right] > aim)
                    {
                        right--;
                    }
                    else
                    {
                        ans.push_back({ nums[i],nums[j],nums[left],nums[right] });
                        left++;
                        while (left < right && nums[left] == nums[left - 1])
                        {
                            left++;
                        }
                        right--;
                        while (left < right && nums[right] == nums[right + 1])
                        {
                            right--;
                        }
                    }
                }

                j++;
                while (j < len - 2 && nums[j] == nums[j - 1])
                {
                    j++;
                }
            }

            i++;
            while (i < len - 3 && nums[i] == nums[i - 1])
            {
                i++;
            }
        }
        return ans;
    }
};